package com.fr.lintcode;

import org.junit.Test;

/**
*作者：furong
*日期：2017年1月13日
*时间：上午11:11:32
*/
public class Q96 {
    /**
     * @param head: The first node of linked list.
     * @param x: an integer
     * @return: a ListNode 
     */
    public ListNode partition(ListNode head, int x) {
        if (head == null) {
            return null;
        }
        ListNode pmin = null;
        ListNode min = null;
        ListNode pmax = null;
        ListNode max = null;
        while (head != null) {
            if (head.val < x) {
                if (min == null) {
                    min = head;
                    pmin = min;
                } else {
                    min.next = head;
                    min = min.next;
                }
            } else {
                if (max == null) {
                    max = head;
                    pmax = max;
                } else {
                    max.next = head;
                    max = max.next;
                }
            }
            head = head.next;
        }
        if (pmin == null) {
            max.next = null;
            return pmax;
        }
        if (pmax == null) {
            min.next = null;
            return pmin;
        }
        max.next = null;
        min.next = pmax;
        return pmin;
    }

    @Test
    public void testA() {
        ListNode head = new ListNode(1);
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(3);
        ListNode l3 = new ListNode(4);
        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(3);
        ListNode l6 = new ListNode(2);
        head.next = l1;
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        int x = 3;
        System.out.println(head);
        ListNode rs = partition(head, x);
        System.out.println(rs);
    }
}
